const db = require('../db');

// 获取商品的拼团状态
exports.getGroupBuyStatus = async (product_id) => {
    const [rows] = await db.promise().query(
        `SELECT 
            g.*,
            u.username as creator_name,
            u.user_id as creator_user_id,
            DATE_FORMAT(g.end_time, '%Y-%m-%d %H:%i:%s') as formatted_end_time
         FROM groupbuy g
         JOIN users u ON g.creator_user_id = u.user_id
         WHERE g.product_id = ? 
         AND g.status = 'in_progress'
         ORDER BY g.created_at DESC 
         LIMIT 1`,
        [product_id]
    );
    return rows[0];
};

// 获取拼团参与者
exports.getParticipants = async (groupbuy_id) => {
    const [rows] = await db.promise().query(
        `SELECT 
            u.user_id, 
            u.username, 
            gp.join_time,
            DATE_FORMAT(gp.join_time, '%Y-%m-%d %H:%i:%s') as formatted_join_time
         FROM groupbuy_participants gp
         JOIN users u ON gp.user_id = u.user_id
         WHERE gp.groupbuy_id = ?
         ORDER BY gp.join_time`,
        [groupbuy_id]
    );
    return rows;
};

// 创建拼团活动
exports.createGroupBuy = async ({ product_id, creator_user_id, end_time }) => {
    const [result] = await db.promise().query(
        `INSERT INTO groupbuy 
         (product_id, creator_user_id, end_time, status, current_count) 
         VALUES (?, ?, ?, 'in_progress', 1)`,
        [product_id, creator_user_id, end_time]
    );

    // 创建者自动加入拼团
    await db.promise().query(
        `INSERT INTO groupbuy_participants (groupbuy_id, user_id)
         VALUES (?, ?)`,
        [result.insertId, creator_user_id]
    );

    return result.insertId;
};

// 检查是否已参与拼团
exports.isParticipant = async (groupbuy_id, user_id) => {
    const [rows] = await db.promise().query(
        `SELECT COUNT(*) as count 
         FROM groupbuy_participants 
         WHERE groupbuy_id = ? AND user_id = ?`,
        [groupbuy_id, user_id]
    );
    return rows[0].count > 0;
};

// 加入拼团
exports.joinGroupBuy = async (groupbuy_id, user_id) => {
    const connection = await db.promise().getConnection();
    try {
        await connection.beginTransaction();

        // 添加参与记录
        await connection.query(
            `INSERT INTO groupbuy_participants (groupbuy_id, user_id)
             VALUES (?, ?)`,
            [groupbuy_id, user_id]
        );

        // 更新当前参与人数
        await connection.query(
            `UPDATE groupbuy 
             SET current_count = current_count + 1
             WHERE groupbuy_id = ?`,
            [groupbuy_id]
        );

        await connection.commit();
    } catch (error) {
        await connection.rollback();
        throw error;
    } finally {
        connection.release();
    }
};

// 更新拼团状态
exports.updateGroupBuyStatus = async (groupbuy_id, status) => {
    await db.promise().query(
        `UPDATE groupbuy SET status = ? WHERE groupbuy_id = ?`,
        [status, groupbuy_id]
    );
};

// 获取拼团详情
exports.getGroupBuyById = async (product_id) => {
    console.log("product_id", product_id);

    const [rows] = await db.promise().query(
        `SELECT g.*, u.username AS creator_name 
FROM groupbuy g
JOIN users u ON g.creator_user_id = u.user_id
WHERE g.product_id = ?
  AND g.current_count != 3
  AND DATE(g.end_time) > CURDATE()`,
        [product_id]
    );
    return rows;
}; 